package com.htfyun.ft.fragment.factory;

import android.content.Context;
import android.net.wifi.ScanResult;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.htfyun.ft.R;
import com.htfyun.ft.config.FTBuildConfig;
import com.htfyun.ft.utils.DebugLog;
import com.htfyun.ft.wifilibrary.OnWifiStatusListener;
import com.htfyun.ft.wifilibrary.OnWifiScanResultsListener;
import com.htfyun.ft.wifilibrary.WiFiManager;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

public class FragmentWifi extends FactoryBaseFragment  implements SwipeRefreshLayout.OnRefreshListener {

    private WiFiManager mWiFiManager;

    private TextView txtStatus;
    private TextView txtAutoTestSSID;

    private SwipeRefreshLayout swipeRefreshLayout;

    private ListView mWifiListView;
    private WifiListAdapter mWifiListAdapter;

    @Override
    protected int getLayoutRes() {
        return R.layout.fragment_factory_wifi;
    }

    @Override
    protected void onInitView(@Nullable Bundle savedInstanceState) {
        super.onInitView(savedInstanceState);

        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
        swipeRefreshLayout.setOnRefreshListener(this);

        txtStatus = (TextView) findViewById(R.id.txtStatus);
        txtAutoTestSSID = (TextView) findViewById(R.id.txtAutoTestSSID);
        txtAutoTestSSID.setText(getString(R.string.wifi_auto_pass_scan_ssid, FTBuildConfig.WIFI_SSID_PASSED));

        mWifiListView = (ListView) findViewById(R.id.wifiListView);
        mWifiListView.setEmptyView(findViewById(R.id.empty_view));
        mWifiListAdapter = new WifiListAdapter(getContext());
        mWifiListView.setAdapter(mWifiListAdapter);

        mWiFiManager = WiFiManager.getInstance();

        setBtnPassVisibility(View.GONE);

    }

    @Override
    protected void onVisible() {
        super.onVisible();

        mWiFiManager.registerWifiReceiver();

        mWiFiManager.addOnWifiStatusListener(enabledListener);
        mWiFiManager.addOnWifiScanResultsListener(scanResultsListener);

        wifiStartScan();

    }

    @Override
    protected void onInvisible() {
        super.onInvisible();

        mWiFiManager.unregisterWifiReceiver();
        mWiFiManager.removeOnWifiStatusListener(enabledListener);
        mWiFiManager.removeOnWifiScanResultsListener(scanResultsListener);

    }

    private OnWifiStatusListener enabledListener =
            new OnWifiStatusListener() {
                @Override
                public void onWifiEnabled(WifiStatusAttr status) {
                    int statusResId = R.string.wifi_status_off;
                    if (status == WifiStatusAttr.enabled) {
                        statusResId = R.string.wifi_status_on;
                        mWiFiManager.startScan();
                    }

                    txtStatus.setText(getString(R.string.wifi_status, getString(statusResId)));
                }
            };

    private OnWifiScanResultsListener scanResultsListener =
            new OnWifiScanResultsListener() {
                @Override
                public void onScanResults(List<ScanResult> scanResults) {
                    DebugLog.e("aa scanResults size = " + scanResults.size());

                    refreshData(scanResults);

                    for (ScanResult scanResult : scanResults) {
                        String ssid = scanResult.SSID.replaceAll("\"", "");

                        DebugLog.e("ssid = " + ssid + ", level = " + scanResult.level
                                + ", FTBuildConfig.WIFI_SSID_PASSED_HTFYUN = " + FTBuildConfig.WIFI_SSID_PASSED_HTFYUN);

                        if (scanResult.level > (FTBuildConfig.WIFI_RSSI_MIN)
                                && (ssid.equals(FTBuildConfig.WIFI_SSID_PASSED) || ssid.equals(FTBuildConfig.WIFI_SSID_PASSED_HTFYUN))) {

                            delayAutoPass();
                            break;
                        }
                    }
                }
            };

    @Override
    public void onRefresh() {
        // 下拉刷新
        mWiFiManager.startScan();

        mWifiListAdapter.clearData();

    }

    private void wifiStartScan() {

        int statusResId = R.string.wifi_status_on;

        if (!mWiFiManager.isWifiEnabled()) {
            statusResId = R.string.wifi_status_off;
            mWiFiManager.openWiFi();
        } else {

            mWiFiManager.startScan();
        }

        txtStatus.setText(getString(R.string.wifi_status, getString(statusResId)));
    }

    private void refreshData(List<ScanResult> scanResults) {
        swipeRefreshLayout.setRefreshing(false);
        // 刷新界面
        mWifiListAdapter.refreshData(scanResults);
    }

    private final class WifiListAdapter extends BaseAdapter {

        private List<ScanResult> scanResults;
        private Context mContext;

        public WifiListAdapter(Context context) {
            mContext = context.getApplicationContext();
            this.scanResults = new ArrayList<>();
        }

        public List<ScanResult> getScanResults() {
            return scanResults;
        }

        private List<ScanResult> getNewScanResultBySetConnectedSSIDFist(List<ScanResult> scanResults) {

            Collections.sort(scanResults, new Comparator<ScanResult>() {
                @Override
                public int compare(ScanResult o1, ScanResult o2) {
                    return o2.level- o1.level;
                }
            });

            return scanResults;

        }

        public void clearData() {
            scanResults.clear();
            notifyDataSetChanged();
        }

        public void refreshData(List<ScanResult> scanResults) {
            if (null != scanResults) {
                // 去重
                List<ScanResult> newScanResults = WiFiManager.excludeRepetition(scanResults);

                // 清空数据
                this.scanResults.clear();
                // 更新数据
                this.scanResults.addAll(getNewScanResultBySetConnectedSSIDFist(newScanResults));
            }
            // 更新显示
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return scanResults.size();
        }

        @Override
        public Object getItem(int position) {
            return scanResults.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView != null) {
                holder = (ViewHolder)convertView.getTag();
            }

            if (holder == null) {
                holder = new ViewHolder();
                LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(R.layout.item_wifi_devices, null);
                holder.txtName = (TextView) convertView.findViewById(R.id.txtName);
                holder.txtRSSI = (TextView) convertView.findViewById(R.id.txtRSSI);
                holder.txtCapabilities = (TextView) convertView.findViewById(R.id.txtCapabilities);

                convertView.setTag(holder);
            }

            ScanResult scanResult = scanResults.get(position);

            holder.txtName.setText(getString(R.string.wifi_rssi_name, scanResult.SSID));

            holder.txtRSSI.setText(getString(R.string.wifi_signal_strength, scanResult.level));//(WifiManager.calculateSignalLevel(scanResult.level, 5) + "/5")));
            holder.txtCapabilities.setText(getString(R.string.wifi_capabilities, scanResult.capabilities));

            return convertView;
        }
    }

    private class ViewHolder {
        private TextView txtName;
        private TextView txtRSSI;
        private TextView txtCapabilities;
    }
}
